<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>健康档案</h2>
          <el-button 
            type="primary" 
            @click="toggleEdit"
            icon="el-icon-edit"
          >
            {{ editing ? '取消编辑' : '编辑信息' }}
          </el-button>
        </div>
      </template>

      <el-form 
        v-if="editing"
        :model="editForm" 
        label-width="120px"
        :rules="rules"
        ref="formRef"
        class="edit-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="血型" prop="bloodType">
              <el-select v-model="editForm.bloodType" placeholder="请选择血型">
                <el-option label="A型" value="A型"></el-option>
                <el-option label="B型" value="B型"></el-option>
                <el-option label="AB型" value="AB型"></el-option>
                <el-option label="O型" value="O型"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="既往病史" prop="medicalHistory">
              <el-input 
                v-model="editForm.medicalHistory" 
                type="textarea" 
                :rows="3"
                placeholder="请输入既往病史，如无请填'无'"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="过敏史" prop="allergyHistory">
              <el-input 
                v-model="editForm.allergyHistory" 
                type="textarea" 
                :rows="3"
                placeholder="请输入过敏史，如无请填'无'"
              ></el-input>
            </el-form-item>
            <el-form-item label="身高体重" class="height-weight-group">
              <el-input-number 
                v-model="editForm.height" 
                :min="100" 
                :max="250" 
                :step="1"
                placeholder="身高(cm)"
              ></el-input-number>
              <span style="margin: 0 10px">/</span>
              <el-input-number 
                v-model="editForm.weight" 
                :min="30" 
                :max="200" 
                :step="1"
                placeholder="体重(kg)"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item class="form-actions">
          <el-button type="primary" @click="submitEdit">保存修改</el-button>
          <el-button @click="toggleEdit">取消</el-button>
        </el-form-item>
      </el-form>

      <el-descriptions 
        v-else
        :column="2" 
        border
        class="info-display"
      >
        <el-descriptions-item label="血型">{{ baseInfo.bloodType || '暂无数据' }}</el-descriptions-item>
        <el-descriptions-item label="既往病史">{{ baseInfo.medicalHistory || '无' }}</el-descriptions-item>
        <el-descriptions-item label="过敏史">{{ baseInfo.allergyHistory || '无' }}</el-descriptions-item>
        <el-descriptions-item label="身高体重">{{ baseInfo.height }}cm / {{ baseInfo.weight }}kg</el-descriptions-item>
      </el-descriptions>

      <!-- 健康记录卡片 -->
      <el-card>
        <template #header>
          <div class="card-header">
            <h2>健康记录历史</h2>
          </div>
        </template>
        
        <el-table 
          :data="healthData" 
          border 
          stripe 
          style="width: 100%"
          v-loading="loading"
          element-loading-text="数据加载中..."
          element-loading-background="rgba(255, 255, 255, 0.8)"
        >
          <el-table-column 
            prop="recordDate" 
            label="记录日期" 
            width="150" 
            align="center"
          ></el-table-column>
          
          <el-table-column 
            prop="staffName"
            label="负责护工" 
            width="120"
            align="center"
          >

          </el-table-column>
          
          <el-table-column 
            prop="bloodPressure" 
            label="血压(mmHg)" 
            width="120"
            align="center"
          >
            <template #default="{row}">
              <el-tag v-if="row.bloodPressure" type="info">
                {{ row.bloodPressure }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column 
            prop="heartRate" 
            label="心率(bpm)" 
            width="110"
            align="center"
          >
            <template #default="{row}">
              <div :class="{'warning-text': row.heartRate > 100}">
                {{ row.heartRate || '-' }}
              </div>
            </template>
          </el-table-column>
          
          <el-table-column 
            prop="bloodSugar" 
            label="血糖(mmol/L)" 
            width="130"
            align="center"
          >
            <template #default="{row}">
              <div :class="{
                'warning-text': row.bloodSugar > 6.1 || row.bloodSugar < 3.9
              }">
                {{ row.bloodSugar?.toFixed(1) || '-' }}
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="doctorSuggestions" label="医生建议">
            <template #default="{row}">
              <div style="white-space: pre-wrap;">{{ row.doctorSuggestions || '暂无建议' }}</div>
            </template>
          </el-table-column>
        </el-table>

        <div style="margin-top: 20px">
          <el-pagination
              @current-change="currentChange"
              @size-change="sizeChange"
              :page-size="pageInfo.pageSize"
              :current-page="pageInfo.pageNum"
              background
              layout="total,sizes, prev, pager, next"
              :total="pageInfo.total">
          </el-pagination>
        </div>
      </el-card>
    </el-card>
  </div>
</template>

<script setup>
import {ref, onMounted, reactive, toRaw} from 'vue'
import http from '@/utils/http.js'
import utils from "@/utils/tools.js";
import { ElMessage } from 'element-plus'

const editing = ref(false)
const baseInfo = ref({
  bloodType: '',
  medicalHistory: '',
  allergyHistory: '',
  height: '-',
  weight: '-'
})

const healthData = ref([])

const pageInfo = ref({
  //当前页
  pageNum: 1,
  //分页大小
  pageSize: 10,
  //总条数
  total: 0
});

const loading = ref(false)

const editForm = reactive({ ...baseInfo.value })
const rules = {
  bloodType: [{ required: true, message: '请选择血型', trigger: 'change' }],
  medicalHistory: [{ required: true, message: '请输入既往病史', trigger: 'blur' }],
  allergyHistory: [{ required: true, message: '请输入过敏史', trigger: 'blur' }],
  height: [
    { required: true, message: '请输入身高', trigger: 'blur' },
    { type: 'number', min: 100, max: 250, message: '身高应在100-250cm之间', trigger: 'blur' }
  ],
  weight: [
    { required: true, message: '请输入体重', trigger: 'blur' },
    { type: 'number', min: 30, max: 200, message: '体重应在30-200kg之间', trigger: 'blur' }
  ]
}

onMounted(() => {
  getElderInfo()
})

async function getElderInfo() {
  try {
    const res = await http.get(`/elder/selectById/${utils.getCurrentUser().id}`)
    const data = res.data
    baseInfo.value = {
      bloodType: data.bloodType || '未知',
      medicalHistory: data.medicalHistory || '无',
      allergyHistory: data.allergyHistory || '无',
      height: data.height || '-',
      weight: data.weight || '-'
    }
  } catch (e) {
    console.error('获取基本信息失败:', e)
    ElMessage.error('基本信息加载失败')
  }
}

getPageList()

/**
 * 选择分页
 * @param e
 */
function currentChange(e) {
  pageInfo.value.pageNum = e
  getPageList()
}

/**
 * 改变分页数量
 * @param e
 */
function sizeChange(e) {
  pageInfo.value.pageSize = e
  getPageList()
  console.log(e)
}

/**
 * 搜索
 */
function search() {
  pageInfo.value.pageNum = 1
  getPageList()
}

/**
 * 重置搜索框
 */
function resetSearch() {
  searchFormComponents.value.resetFields();
  getPageList()
}

/**
 * 获取分页数据
 */
async function getPageList() {
  loading.value = true
  try {
    const params = {
      pageNum: pageInfo.value.pageNum,
      pageSize: pageInfo.value.pageSize,
      elderId: utils.getCurrentUser().id,
    }
    console.log('请求参数:', params)
    const res = await http.get(`/health_record/page`, { params })
    healthData.value = res.data.list
    pageInfo.value.total = res.data.total
    console.log('响应数据:', res.data)
  } catch (e) {
    console.error('获取数据失败:', e)
  } finally {
    loading.value = false
  }
}

function toggleEdit() {
  editing.value = !editing.value
  if (editing.value) {
    Object.assign(editForm, baseInfo.value)
  }
}

async function submitEdit() {
  try {
    await http.put('/elder/update', editForm)
    Object.assign(baseInfo.value, editForm)
    editing.value = false
    ElMessage.success('修改成功')
  } catch (e) {
    ElMessage.error('修改失败')
  }
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.warning-text {
  color: #e6a23c;
  font-weight: 500;
}

.el-col {
  padding: 0 20px;
}

.edit-form {
  margin-bottom: 20px;
}

.info-display {
  margin-bottom: 20px;
}

.height-weight-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.form-actions {
  margin-top: 20px;
  text-align: right;
}
</style> 